// 封装请求
import { ElMessage } from 'element-plus'
import type {UseFetchOptions} from "#app";


export interface ResponseConfig {
    code: number,
    status: number,
    data: any,
    message: string

}
let reqUrl: string

const fetch = async(url: string | (() => string), options?: UseFetchOptions<any>): Promise<any> => {
    const headers = {
        "Content-Type": "application/json;charset=utf-8",
        'X-Requested-With': 'XMLHttpRequest',
        'Access-Control-Allow-Origin': '*'
    }
    const api = 'https://service.starbucket.cn'
    const localhost = 'http://localhost:8000'
    reqUrl = localhost + url
    return new Promise(async (resolve, reject) => {
        try {
            await useFetch(reqUrl,
                { ...options , headers, $fetch: useNuxtApp().$api as typeof $fetch}).then(({data, error }: any) => {
                const value = data.value
                // return
                if (value.code !== 200) {
                    // 这里处理错误回调
                    ElMessage({
                        message: value.message,
                        type: 'error',
                        duration: 1000,
                    })
                    reject(value)
                }
                else {
                    resolve(ref(value))
                }
            }).catch((error: any) => {
                reject(error)
            })
        }
        catch (e) {
            console.log(e)
        }
    })
}

export default new class Http {

    get(url: string, params?: any): Promise<any> {
        return fetch(url, { method: 'GET', params})
    }

    post(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'POST', body })
    }

    put(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'PUT', body })
    }

    delete(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'DELETE', body })
    }
}